package com.wgl.db.pojo;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.http.client.ClientProtocolException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wgl.utl.Tool;

public class Train {

	// 4.车号
	// 9.始发时间
	// 10.到大时间
	// 11.总耗时
	// 14.日期
	// 22.高级软卧
	// 24.软卧
	// 27.无座
	// 29.硬卧
	// 30.硬座
	// 31.二等座
	// 32.一等座
	// 33.商务座
	// 34.动卧
	// 时间使用需要减一

	public static final int MAX_TICKET_NUM = 20;

	public static final int COLUMN_NUM = 37;
	// 8,13,
	public static final String[] TITLE_ARRAY = { "车号", "始发时间", "到达时间", "总耗时", "日期", "高级软卧", "软卧", "无座", "硬卧", "硬座",
			"二等座", "一等座", "商务座", "动卧" };
	public static final int[] ORDER = { 3, 8, 9, 10, 13, 21, 23, 26, 28, 29, 30, 31, 32, 33 };

	public static final int[] CONDITION = { 3, 8, 9, 10, 13 };
	// 座位类型
	public static final int TYPE_SEAT_ALL = -1;

	public static final int TYPE_FIRST_CLASS_BED = 21;

	public static final int TYPE_SOFT_BED = 23;

	public static final int TYPE_NO_SEAT = 26;

	public static final int TYPE_HARD_BAD = 28;

	public static final int TYPE_HARD_SEAT = 29;

	public static final int TYPE_SECOND_SEAT = 30;

	public static final int TYPE_FIRST_SEAT = 31;

	public static final int TYPE_BUSS_SEAT = 32;

	public static final int TYPE_D_SEAT = 33;

	public static final int[] SEAT_TYPE = { TYPE_FIRST_CLASS_BED, TYPE_SOFT_BED, TYPE_NO_SEAT, TYPE_HARD_BAD,
			TYPE_HARD_SEAT, TYPE_SECOND_SEAT, TYPE_FIRST_SEAT, TYPE_BUSS_SEAT, TYPE_D_SEAT };

	public static final String[] SEAT_TYPE_NAME = { "高级软卧", "软卧", "无座", "硬卧", "硬座", "二等座", "一等座", "商务座", "动卧" };

	private String trainCode = null;
	private String startTime = null;
	private String endTime = null;
	private List<String> stations = new ArrayList<String>();
	private int totalTime = 0;
	private String trainDate = null;
	private String fromStation = null;
	private String fromStationName = null;
	private String toStation = null;
	private String toStationName = null;
	private int firstClass = 0;
	private int softBed = 0;
	private int noSeat = 0;
	private int hardBed = 0;
	private int hardSeat = 0;
	private int secondSeat = 0;
	private int firstSeat = 0;
	private int bussSeat = 0;
	private int dSeat = 0;
	private boolean hasTicket = false;
	private final static String QUERY_LINK = "/otn/leftTicket/query";
	private final static String DOMAIN_12306_QUERY = "kyfw.12306.cn";

	public Train(String trainInfoStr, JSONObject map) throws ParseException {
		this(trainInfoStr.split("\\|"), map);
	}

	/**
	 * 构造方法,根据
	 * 
	 * @param trainStr
	 * @throws ParseException
	 */
	public Train(String[] trainStr, JSONObject map) throws ParseException {
		this.trainCode = trainStr[3];
		this.stations.add(trainStr[4].trim());
		this.stations.add(trainStr[5].trim());
		this.stations.add(trainStr[6].trim());
		this.stations.add(trainStr[7].trim());
		this.startTime = trainStr[8];
		this.endTime = trainStr[9];
		this.totalTime = _getTotalTime(trainStr[10]);
		this.trainDate = Tool.DateUtil.getDateStringByPattern(trainStr[13], "yyyyMMdd", "yyyy-MM-dd");
		this.firstClass = _getTicketNum(trainStr[21]);
		this.softBed = _getTicketNum(trainStr[23]);
		this.noSeat = _getTicketNum(trainStr[26]);
		this.hardBed = _getTicketNum(trainStr[28]);
		this.hardSeat = _getTicketNum(trainStr[29]);
		this.secondSeat = _getTicketNum(trainStr[30]);
		this.firstSeat = _getTicketNum(trainStr[31]);
		this.bussSeat = _getTicketNum(trainStr[32]);
		this.dSeat = _getTicketNum(trainStr[33]);
		this.hasTicket = this._hasTicket();
		this._getStationName(map);
	}

	/**
	 * 获取当天车次列表
	 * 
	 * @param condition
	 * @return
	 * @throws ClientProtocolException
	 * @throws URISyntaxException
	 * @throws IOException
	 * @throws ParseException
	 */
	public static List<Train> getTrainList(LinkedHashMap<String, String> condition)
			throws ClientProtocolException, URISyntaxException, IOException, ParseException {
		String content = Tool.NetUtil.getURLContent(condition, DOMAIN_12306_QUERY, QUERY_LINK, "https");
		if (!Tool.StringUtil.validStr(content)) {
			return null;
		}
		JSONObject jsonContent = JSONObject.parseObject(content);
		// "validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":
		int httpstatus = jsonContent.getIntValue("httpstatus");
		boolean status = jsonContent.getBooleanValue("status");
		List<Train> trainList = new ArrayList<Train>();
		if (httpstatus == 200 && status) {
			JSONObject data = jsonContent.getJSONObject("data");
			if (data == null) {
				return trainList;
			}
			JSONArray resultArray = data.getJSONArray("result");
			JSONObject map = data.getJSONObject("map");
			// 站点代号
			for (int i = 0; i < resultArray.size(); i++) {
				String temp = (String) resultArray.get(i);
				if (!temp.contains("列车停运")) {
					trainList.add(new Train(temp, map));
				}
			}
		}
		return trainList;
	}

	/**
	 * 获取具体的车次,并查询符合条件的车次
	 * 
	 * @param contentArr
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 * @throws URISyntaxException
	 * @throws ClientProtocolException
	 */
	public static Train getTargetTrainListByCondition(LinkedHashMap<String, String> condition, String targetTrainCode,
			int seatCondition) throws ParseException, ClientProtocolException, URISyntaxException, IOException {
		String content = Tool.NetUtil.getURLContent(condition, DOMAIN_12306_QUERY, QUERY_LINK, "https");
		if (!Tool.StringUtil.validStr(content)) {
			return null;
		}
		JSONObject jsonContent = JSONObject.parseObject(content);
		// "validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":
		int httpstatus = jsonContent.getIntValue("httpstatus");
		boolean status = jsonContent.getBooleanValue("status");
		if (httpstatus == 200 && status) {
			JSONObject data = jsonContent.getJSONObject("data");
			JSONArray resultArray = data.getJSONArray("result");
			JSONObject map = data.getJSONObject("map");
			// 站点代号
			for (int i = 0; i < resultArray.size(); i++) {
				String temp = (String) resultArray.get(i);
				if (!temp.contains("列车停运")) {
					Train train = new Train(temp, map);
					if (train.getTrainCode().equals(targetTrainCode) && train.hasTicket()) {
						return train;
					}
				}
			}
		}
		return null;
	}

	private void _getStationName(JSONObject map) {
		int cnt = 0;
		for (String temp : stations) {
			if (map.containsKey(temp)) {
				String value = map.getString(temp);
				if (cnt == 0) {
					this.fromStation = temp;
					this.fromStationName = value;
					cnt++;
				} else if (cnt == 1) {
					this.toStation = temp;
					this.toStationName = value;
					break;
				} else {
					break;
				}
			}
		}
	}

	/**
	 * 是否有票
	 * 
	 * @return
	 */
	private boolean _hasTicket() {
		if (firstClass > 0 || softBed > 0 || noSeat > 0 || hardBed > 0 || hardSeat > 0 || secondSeat > 0
				|| firstSeat > 0 || bussSeat > 0 || dSeat > 0) {
			return true;

		}
		return false;
	}

	private int _getTicketNum(String ticketNUm) {
		String temp = ticketNUm.trim();
		int leftTicket = 0;
		if (Tool.StringUtil.validStr(temp)) {
			if ("有".equals(temp)) {
				leftTicket = 20;
			} else if (!"无".equals(temp)) {
				leftTicket = Integer.valueOf(temp);
			}
		}
		return leftTicket;
	}

	private int _getTotalTime(String totalTime) {
		String[] time = totalTime.split(":");
		int hours = Integer.valueOf(time[0]);
		int minutes = Integer.valueOf(time[1]);
		return hours * 60 + minutes;
	}

	public boolean hasTicket() {
		return hasTicket;
	}

	public String getFromStationName() {
		return fromStationName;
	}

	public String getToStationName() {
		return toStationName;
	}

	public String getTrainCode() {
		return trainCode;
	}

	public String getStartTime() {
		return startTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public int getTotalTime() {
		return totalTime;
	}

	public String getTrainDate() {
		return trainDate;
	}

	public String getFromStation() {
		return fromStation;
	}

	public String getToStation() {
		return toStation;
	}

	public int getFirstClass() {
		return firstClass;
	}

	public int getSoftBed() {
		return softBed;
	}

	public int getNoSeat() {
		return noSeat;
	}

	public int getHardBed() {
		return hardBed;
	}

	public int getHardSeat() {
		return hardSeat;
	}

	public int getSecondSeat() {
		return secondSeat;
	}

	public int getFirstSeat() {
		return firstSeat;
	}

	public int getBussSeat() {
		return bussSeat;
	}

	public int getdSeat() {
		return dSeat;
	}

}
